﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Write.Api.Application.Command.OutsourcingCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;

namespace B.S.Orders.Write.Api.Controllers
{
    /// <summary>
    /// 委外控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OutsourcingController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ISqlSugarClient db;

        public OutsourcingController(IMediator mediator, ISqlSugarClient db)
        {
            this.mediator = mediator;
            this.db = db;
        }

        /// <summary>
        /// 添加委外
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> AddOutsourcing(AddOutsourcingCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 添加委外明细表
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> AddOutsourcingDetail(AddOutsourcingDetailCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除委外信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> DelOutsourcing(DelOutsourcingCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 修改委外信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> UpdateOutsourcing(UpdateOutsourcingCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 修改委外明细信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> UpdateOutsourcingDetail(UpdateOutsourcingDetailCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 导入方法
        /// </summary>
        /// <param name="file"></param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public IActionResult ImportExcel(IFormFile file)
        {
            try
            {
                if (file != null && file.Length > 0)
                {

                    // 读取 Excel 文件
                    using (var stream = new MemoryStream())
                    {
                        file.CopyTo(stream);
                        stream.Position = 0;
                        using (var workbook = new XSSFWorkbook(stream))
                        {
                            var sheet = workbook.GetSheetAt(0);
                            var production = new List<Outsourcing>();

                            // 从第二行开始读取数据，跳过表头
                            for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
                            {
                                var row = sheet.GetRow(rowIndex);
                                if (row != null)
                                {
                                    var user = new Outsourcing
                                    {
                                        DocumentSubject = GetCellValueAsString(row.GetCell(1)),
                                        DocumentNumber = GetCellValueAsString(row.GetCell(2)),
                                        AssociateProductionOrder = GetCellValueAsString(row.GetCell(3)),
                                        Processors = GetCellValueAsString(row.GetCell(4)),
                                        Client = GetCellValueAsString(row.GetCell(5)),
                                        OurRepresentatives = GetCellValueAsString(row.GetCell(6)),
                                        PaymentPlan = GetCellValueAsString(row.GetCell(7)),
                                        TicketCollectionPlan = GetCellValueAsString(row.GetCell(8)),
                                        AutomaticallyReceivedInspection = GetCellValueAsBoolean(row.GetCell(9)),
                                        WhetherMaterials = GetCellValueAsBoolean(row.GetCell(10)),
                                        DateOutsourcing = GetCellValueAsDateTime(row.GetCell(11)),
                                        PreparationDocumentsDate = GetCellValueAsDateTime(row.GetCell(12)),
                                        PreparationDocumentsPerson = GetCellValueAsString(row.GetCell(13)),
                                        AssociatedProjects = GetCellValueAsString(row.GetCell(14)),
                                        Remark = GetCellValueAsString(row.GetCell(15)),
                                        DocumentsId = GetCellValueAsInt(row.GetCell(16)),
                                    };
                                    production.Add(user);
                                }
                            }

                            // 批量插入数据到数据库
                            db.Insertable(production).ExecuteCommand();
                        }
                    }

                    return Ok("导入成功");
                }
                return BadRequest("请选择要导入的 Excel 文件");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"导入失败: {ex.Message}");
            }
        }

        //导入datetime类型转换
        private DateTime GetCellValueAsDateTime(ICell cell)
        {
            if (cell == null)
            {
                return DateTime.MinValue;
            }
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    if (NPOI.SS.UserModel.DateUtil.IsCellDateFormatted(cell))
                    {
                        // 新增 ?? DateTime.MinValue 处理 null 情况
                        return cell.DateCellValue ?? DateTime.MinValue;
                    }
                    return DateTime.MinValue;
                case CellType.String:
                    if (DateTime.TryParse(cell.StringCellValue, out DateTime result))
                    {
                        return result;
                    }
                    return DateTime.MinValue;
                default:
                    return DateTime.MinValue;
            }
        }

        //导入bool类型转换
        private bool GetCellValueAsBoolean(ICell cell)
        {
            if (cell == null)
            {
                return false;
            }
            switch (cell.CellType)
            {
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.String:
                    string value = cell.StringCellValue.Trim().ToLower();
                    if (value == "true" || value == "删除" || value == "已生成" || value == "自动生成订单")
                    {
                        return true;
                    }
                    else if (value == "false" || value == "未删除" || value == "未生成")
                    {
                        return false;
                    }
                    return false;
                default:
                    return false;
            }
        }

        //导入string类型数据转换
        private string GetCellValueAsString(ICell cell)
        {
            if (cell == null)
            {
                return string.Empty;
            }
            switch (cell.CellType)
            {
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue.ToString();
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Formula:
                    return cell.CellFormula;
                default:
                    return string.Empty;
            }
        }

        //导入int类型数据转换
        private int GetCellValueAsInt(ICell cell)
        {
            if (cell == null)
            {
                return 0;
            }
            switch (cell.CellType)
            {
                case CellType.Numeric:
                    return (int)cell.NumericCellValue;
                case CellType.String:
                    if (int.TryParse(cell.StringCellValue, out int result))
                    {
                        return result;
                    }
                    return 0;
                default:
                    return 0;
            }
        }
    }
}
